package com.beiyou.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.beiyou.dto.UserDto;
import com.beiyou.dto.UserDtoQuery;
import com.beiyou.dto.UserLogin;
import com.beiyou.entity.UserEntity;
import com.beiyou.service.UserService;
import com.github.pagehelper.PageInfo;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wzby
 * @Date: 2022/10/17 10:58
 */
@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired
    private UserService userService;

    @Value("${beiyou.token.secret}")
    private  String TOKEN_SECRET ;

    @GetMapping
    public List<UserDto> select(UserDtoQuery userDtoQuery) {
        return userService.select(userDtoQuery);
    }

    @PostMapping
    public Integer insert(@RequestBody UserDto userDto) {
        return userService.insert(userDto);
    }

    @PostMapping("/login")
    public String login(@RequestBody UserLogin userLogin) throws Exception {

        if (ObjectUtil.isEmpty(userLogin.getTel())) {
            throw new Exception("手机号不能为空");
        }
        if (ObjectUtil.isEmpty(userLogin.getPassword())) {
            throw new Exception("密码不能为空");
        }
        UserDtoQuery userDtoQuery = new UserDtoQuery();
        userDtoQuery.setTel(userLogin.getTel());
        userDtoQuery.setPassword(userLogin.getPassword());

        List<UserDto> users = userService.select(userDtoQuery);
        if (ObjectUtil.isEmpty(users)) {
            throw new Exception("手机号密码错误");
        }

        UserDto user = users.get(0);
        String tel = user.getTel();
        tel = tel.substring(0,3)+"****"+tel.substring(7,11);

        Map<String, Object> map = new HashMap<String, Object>();

        map.put("userId", user.getId());
        map.put("tel", tel);
        map.put("nickName",user.getNickName());
        //令牌存在时间
        map.put("expire_time", System.currentTimeMillis() + 1000 * 60 * 60 * 24 * 15);

        String token = JWTUtil.createToken(map, TOKEN_SECRET.getBytes());

        return token;
    }

}
